Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.


In [1]:
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        这道题思路在于更新tmp字符串
        如果没有重复就把字符添加
        如果有重复的,就把重复的前一部分字符串截取
        不管怎么更新tmp字符串,每次都得更新长度
        :type s: str
        :rtype: int
        """
        # s lenght
        s_len = len(s)
        
        if s_len < 2:
            return s_len
        i = 1
        tmp = s[0]
        ans_len = 0
        while i < s_len:
            if s[i] not in tmp:
                tmp +=  s[i]
                i += 1
            else:
                tmp = tmp[tmp.index(s[i]) + 1:]
            tmp_len = len(tmp)
            if tmp_len > ans_len:
                ans_len = tmp_len
        return ans_len

In [2]:
Solution().lengthOfLongestSubstring("ay") # answer is ay 2


Out[2]:
2

In [3]:
Solution().lengthOfLongestSubstring("pwwkew")  # answer is wke 3


Out[3]:
3

In [4]:
Solution().lengthOfLongestSubstring("abcabcbb") # answer is abc 3


Out[4]:
3

In [5]:
Solution().lengthOfLongestSubstring("bbbbb") # answer is b 1


Out[5]:
1

In [6]:
Solution().lengthOfLongestSubstring("a") # answer is ay a 1


Out[6]:
1

In [7]:
Solution().lengthOfLongestSubstring("") # answer is ay 0


Out[7]:
0

In [ ]: